package com.yocard.yxyd.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shehuan.niv.NiceImageView;
import com.umeng.analytics.MobclickAgent;
import com.yocard.yxyd.R;
import com.yocard.yxyd.adapter.SettingAadapter;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.dto.SettingData;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.http.model.response.UserInfoBean;
import com.yocard.yxyd.others.ClassicsHeader;
import com.yocard.yxyd.others.Glide4Engine;
import com.yocard.yxyd.ui.activity.AboutUsActivity;
import com.yocard.yxyd.ui.activity.CertResultActivity;
import com.yocard.yxyd.ui.activity.CertificationActivity;
import com.yocard.yxyd.ui.activity.InviteFriendsActivity;
import com.yocard.yxyd.ui.activity.PushSettingActivity;
import com.yocard.yxyd.ui.activity.SettingActivity;
import com.yocard.yxyd.ui.activity.TopupCenterActivity;
import com.yocard.yxyd.ui.contract.MeContract;
import com.yocard.yxyd.ui.dialog.ShareDialog;
import com.yocard.yxyd.ui.fragment.base.BaseFragment;
import com.yocard.yxyd.ui.presenter.MePresenter;
import com.yocard.yxyd.ui.view.GuideViewBg;
import com.yocard.yxyd.utils.BigDecimalUtil;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.CacheDoubleStaticUtils;
import com.yocard.yxyd.utils.util.ConvertUtils;
import com.yocard.yxyd.utils.util.SPUtils;
import com.yocard.yxyd.utils.util.ScreenUtils;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static com.yocard.yxyd.event.EventCode.REFRESH_USERI_NFO;

/**
 * Created on 2018/12/14.
 * 我的fragment 16/05/04
 */
public class MeFragment extends BaseFragment<MePresenter> implements MeContract.View, SettingAadapter.OnItemClickListener {
    private static final int SELECTED_AVATOR = 0x11;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.refresh_header)
    ClassicsHeader classicsHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.iv_certified)
    ImageView ivCertified;
    @BindView(R.id.iv_avator)
    NiceImageView ivAvator;
    @BindView(R.id.rl_head_layout)
    RelativeLayout rlHeadLayout;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.rv_setting)
    RecyclerView rvSetting;
    @BindView(R.id.guide_view)
    GuideViewBg guideView;

    private UserInfoBean userInfoBean;
    protected String wechatGroup;
    private SettingAadapter settingAadapter;
    private static final int[] settingResIds = {R.mipmap.ic_wode_balance, R.mipmap.ic_wode_certification, R.mipmap.ic_wode_kefu, R.mipmap.ic_wode_wechat,
            R.mipmap.ic_wode_gift, R.mipmap.ic_wode_about, R.mipmap.ic_wode_set, R.mipmap.ic_push_order, R.mipmap.ic_wpde_tool};
    List<SettingData> settingDataList;
    private int guideIndex; //引导步骤

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ft_me;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initEventAndData() {
        boolean showShareGuid = SPUtils.getInstance().getBoolean(Constants.SHOW_SHARE_GIFT_GUID, true);
        if (showShareGuid) {
            guideView.setVisibility(View.VISIBLE);
            int showY = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 415, getContext().getResources().getDisplayMetrics());
            guideView.setShowY(showY);
            guideView.setShowX(ScreenUtils.getScreenWidth() / 2);
        }

        settingDataList = new ArrayList<SettingData>();
        String[] settingArrays = getResources().getStringArray(R.array.settings);
        for (int i = 0; i < settingArrays.length; i++) {
            SettingData data = new SettingData();
            data.setName(settingArrays[i]);
            data.setResId(settingResIds[i]);
            settingDataList.add(data);
        }
        settingAadapter = new SettingAadapter(settingDataList);
        rvSetting.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rvSetting.setAdapter(settingAadapter);
        settingAadapter.setOnItemclick(this);

//        refreshLayout.setEnableLoadMore(false);
        mPresenter.fetchUserData();
        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            mPresenter.fetchUserData();
        });
    }

    @OnClick({R.id.tv_recharge, R.id.iv_avator, R.id.tv_status, R.id.guide_view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_recharge:
                MobclickAgent.onEvent(mContext, "9", "click_topup_page");
                ActivityUtils.startActivity(TopupCenterActivity.class);
                break;
            case R.id.iv_avator:
                mPresenter.selectAvator(this, SELECTED_AVATOR);
                break;
            case R.id.tv_status:
                certification();
                break;
            case R.id.guide_view:
                guideIndex++;
                if (guideIndex == 1) {
                    int showY = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 500, getContext().getResources().getDisplayMetrics());
                    guideView.setShowY(showY);
                } else {
                    guideView.setVisibility(View.GONE);
                }
                SPUtils.getInstance().put(Constants.SHOW_SHARE_GIFT_GUID, false);
                break;
        }
    }

    @Override
    public void onFetchUser(UserInfoBean userInfoBean) {
        this.userInfoBean = userInfoBean;
        if (userInfoBean != null)
            SPUtils.getInstance().put(Constants.USER_PHONE, userInfoBean.getId());
        refreshLayout.finishRefresh();
//        rlCert.setEnabled(true);
        tvStatus.setSelected(false);
        mPresenter.LayoutText(userInfoBean.getApproval_status(), tvStatus);
        tvName.setText(R.string.welcome_join);
        switch (userInfoBean.getApproval_status()) {
            case Constants.AUTH_UNAPPROVED:
                tvStatus.setText(R.string.certification);
                tvStatus.setVisibility(View.VISIBLE);
                ivCertified.setVisibility(View.GONE);
                break;
            case Constants.AUTH_APPROVING:
//                tvName.setText(CommonUtils.getFormatMobile(userInfoBean.getMobile()));
                tvStatus.setText("认证中");
                tvStatus.setVisibility(View.VISIBLE);
                ivCertified.setVisibility(View.GONE);
                break;
            case Constants.AUTH_APPROVED:
                tvName.setText(userInfoBean.getName());
                tvStatus.setText("已认证");
                tvStatus.setVisibility(View.GONE);
                ivCertified.setVisibility(View.VISIBLE);
//                tvAccount.setVisibility(View.VISIBLE);
//                tvAccount.setText(CommonUtils.getFormatMobile(userInfoBean.getMobile()));
//                rlCert.setEnabled(false);
                tvStatus.setSelected(true);
                break;
            case Constants.AUTH_FAILURE:
//                tvName.setText(CommonUtils.getFormatMobile(userInfoBean.getMobile()));
                tvStatus.setText("认证失败");
                tvStatus.setVisibility(View.VISIBLE);
                ivCertified.setVisibility(View.GONE);
                break;
        }
        tvAccount.setText(CommonUtils.getFormatMobile(userInfoBean.getMobile()));
        tvBalance.setText(BigDecimalUtil.getFormatCoin(userInfoBean.getCoin_balance()));
        CacheDoubleStaticUtils.put("mobile", userInfoBean.getMobile());
        if (userInfoBean.getHead() != null && !StringUtils.isEmpty(userInfoBean.getHead().getUrl())) {
            Glide4Engine.getInstance().loadImage(mContext, userInfoBean.getHead().getUrl(), ivAvator);
        }

        wechatGroup = userInfoBean.getWechat_group();
    }

    @Override
    public void onResume() {
        super.onResume();

        ImmersionBar.with(this).statusBarColor(R.color.transparent)
                .statusBarDarkFont(true).init();
    }

    @Override
    public void showErrorMsg(String msg) {
        super.showErrorMsg(msg);
        refreshLayout.finishRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshEvent(CommonBean bean) {
        if (bean.getCode() == Constants.CODE_REFRESH || bean.getCode() == REFRESH_USERI_NFO) {
            mPresenter.fetchUserData();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == SELECTED_AVATOR) {
            List<Uri> uris = Matisse.obtainResult(data);
            List<String> paths = Matisse.obtainPathResult(data);
            Glide4Engine.getInstance().loadThumbnail(mContext, ConvertUtils.dp2px(60)
                    , null, ivAvator, uris.get(0));
            showLoadingDialog();
            mPresenter.uploadAvator(paths.get(0));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onItemClick(SettingData settingData) {
        switch (settingData.getResId()) {
            case R.mipmap.ic_wode_balance:
                MobclickAgent.onEvent(mContext, "9", "click_topup_page");
                ActivityUtils.startActivity(TopupCenterActivity.class);
                break;
            case R.mipmap.ic_wode_certification:
                certification();
                break;
            case R.mipmap.ic_wode_kefu:
                mPresenter.showContact();
                break;
            case R.mipmap.ic_wode_wechat:
                if (!StringUtils.isEmpty(wechatGroup)) {
                    mPresenter.openWx(wechatGroup);
                } else {
                    ToastUtils.showShort("未获取到微信群号");
                }
                break;
            case R.mipmap.ic_wode_share:
                MobclickAgent.onEvent(mContext, "8", "share_weixin");
                if (userInfoBean != null) {
//                    mPresenter.showShare(userInfoBean.getShare_url());
                    if (shareDialog == null) {
                        shareDialog = new ShareDialog(getActivity(), new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                                if (ShareDialog.MOMENTS.equals(value)) {
                                    mPresenter.showShare(userInfoBean.getShare_url(), WechatMoments.NAME);
                                    return;
                                }
                                if (shareDialog.WE_CHAT.equals(value)) {
                                    mPresenter.showShare(userInfoBean.getShare_url(), Wechat.NAME);
                                }
                            }
                        });
                    }
                    shareDialog.show();
                }
                break;
            case R.mipmap.ic_wode_about:
                ActivityUtils.startActivity(AboutUsActivity.class);
                break;
            case R.mipmap.ic_wode_set:
                ActivityUtils.startActivity(SettingActivity.class);
                break;
            case R.mipmap.ic_push_order:
                if (userInfoBean != null) {
                    String approval_status = userInfoBean.getApproval_status();
                    if (Constants.AUTH_UNAPPROVED.equals(approval_status)) {
                        ActivityUtils.startActivity(CertificationActivity.class);
                    } else if (Constants.AUTH_APPROVED.equals(approval_status)) {
                        ActivityUtils.startActivity(PushSettingActivity.class);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("approval_status", approval_status);
                        ActivityUtils.startActivity(bundle, CertResultActivity.class);
                    }
                } else {
                    ToastUtils.showShort(R.string.get_userinfo_failed);
                }
                break;
            case R.mipmap.ic_wode_gift:
                ActivityUtils.startActivity(InviteFriendsActivity.class);
                break;
            default:
                ToastUtils.showShort(R.string.developing);
                break;
        }
    }

    private void certification() {
        if (tvStatus.getText().toString().equals("已认证")) {
            ToastUtils.showShort(R.string.cert_already_successed);
            return;
        }
        MobclickAgent.onEvent(mContext, "11", "click_cert_manager_page");
        if (userInfoBean != null) {
            String approval_status = userInfoBean.getApproval_status();
            if (Constants.AUTH_UNAPPROVED.equals(approval_status)) {
                ActivityUtils.startActivity(CertificationActivity.class);
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("approval_status", approval_status);
                ActivityUtils.startActivity(bundle, CertResultActivity.class);
            }
        }
    }

    private ShareDialog shareDialog;
}
